package com.dh.ch01.framework;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dh.ch01.action.AddAction;

@SuppressWarnings("serial")
public class Controller extends HttpServlet {

	private HashMap<String, Action> actionMap;
	
	public void init(){
		actionMap = new HashMap<String, Action>();
		actionMap.put("add", new AddAction());
	}
	
	private Action determinActionByPath(String path){
		String actionName = path.substring(path.lastIndexOf('/') + 1, path.length() - 7);
		Action action = actionMap.get(actionName);
		return action;
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		StringBuffer path = request.getRequestURL();
		Action action = determinActionByPath(path.toString());
		String result = action.execute(request, response);
		if(null != result){
			request.getRequestDispatcher(result).forward(request, response);
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
}
